# app/routes/feedback_controller.py
from flask import Blueprint, request, jsonify
from app.models.feedback_model import FeedbackOrder
from flask_jwt_extended import jwt_required, get_jwt_identity  # 替换导入
import json

feedback_bp = Blueprint('feedback', __name__)

@feedback_bp.route('/api/feedback/submit', methods=['POST'])
@jwt_required()  # 替换装饰器
def submit_feedback():
    """提交反馈工单"""
    current_user = get_jwt_identity()  # 获取当前用户标识
    data = request.get_json()
    
    # 验证必要字段
    required_fields = ['type', 'buildingName', 'description', 'userId', 'location']
    for field in required_fields:
        if field not in data:
            return jsonify({'code': -1, 'msg': f'缺少必要字段: {field}'})
    
    # 创建工单
    order_id = FeedbackOrder.create_order(data)
    
    if order_id:
        return jsonify({
            'code': 0,
            'msg': '工单提交成功',
            'data': {'orderId': order_id}
        })
    else:
        return jsonify({'code': -1, 'msg': '工单创建失败'})

@feedback_bp.route('/api/feedback/history', methods=['GET'])
@jwt_required()  # 替换装饰器
def get_feedback_history():
    """获取用户的反馈历史"""
    current_user = get_jwt_identity()  # 获取当前用户标识
    user_id = request.args.get('userId')
    
    if not user_id:
        return jsonify({'code': -1, 'msg': '用户ID不能为空'})
    
    orders = FeedbackOrder.get_orders_by_user(user_id)
    
    # 格式化时间
    for order in orders:
        order['createTime'] = order['createTime'].strftime('%Y-%m-%d %H:%M:%S')
        order['updateTime'] = order['updateTime'].strftime('%Y-%m-%d %H:%M:%S')
        # 转换ObjectId为字符串
        if '_id' in order:
            order.pop('_id')
    
    return jsonify({
        'code': 0,
        'data': orders
    })

@feedback_bp.route('/api/feedback/detail', methods=['GET'])
@jwt_required()  # 替换装饰器
def get_feedback_detail():
    """获取工单详情"""
    current_user = get_jwt_identity()  # 获取当前用户标识
    order_id = request.args.get('id')
    
    if not order_id:
        return jsonify({'code': -1, 'msg': '工单ID不能为空'})
    
    order = FeedbackOrder.get_order_by_id(order_id)
    
    if not order:
        return jsonify({'code': -1, 'msg': '工单不存在'})
    
    # 格式化时间
    order['createTime'] = order['createTime'].strftime('%Y-%m-%d %H:%M:%S')
    order['updateTime'] = order['updateTime'].strftime('%Y-%m-%d %H:%M:%S')
    # 转换ObjectId为字符串
    if '_id' in order:
        order.pop('_id')
    
    return jsonify({
        'code': 0,
        'data': order
    })

@feedback_bp.route('/api/feedback/update-status', methods=['POST'])
@jwt_required()  # 替换装饰器
def update_feedback_status():
    """更新工单状态（管理员接口）"""
    current_user = get_jwt_identity()  # 获取当前用户标识
    data = request.get_json()
    
    required_fields = ['orderId', 'status']
    for field in required_fields:
        if field not in data:
            return jsonify({'code': -1, 'msg': f'缺少必要字段: {field}'})
    
    # 验证状态是否合法
    valid_status = ['审核中', '已派单', '已接单', '修复中', '已完成']
    if data['status'] not in valid_status:
        return jsonify({'code': -1, 'msg': f'无效的状态值，必须是：{valid_status}'})
    
    success = FeedbackOrder.update_order_status(
        data['orderId'],
        data['status'],
        data.get('handlerId', ''),
        data.get('log', '')
    )
    
    if success:
        return jsonify({'code': 0, 'msg': '状态更新成功'})
    else:
        return jsonify({'code': -1, 'msg': '状态更新失败，工单不存在'})

@feedback_bp.route('/api/feedback/all', methods=['GET'])
@jwt_required()  # 替换装饰器
def get_all_feedback():
    """获取所有工单（管理员接口）"""
    current_user = get_jwt_identity()  # 获取当前用户标识
    status = request.args.get('status')
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    
    result = FeedbackOrder.get_all_orders(status, page, limit)
    
    # 格式化时间
    for order in result['orders']:
        order['createTime'] = order['createTime'].strftime('%Y-%m-%d %H:%M:%S')
        order['updateTime'] = order['updateTime'].strftime('%Y-%m-%d %H:%M:%S')
        # 转换ObjectId为字符串
        if '_id' in order:
            order.pop('_id')
    
    return jsonify({
        'code': 0,
        'data': {
            'orders': result['orders'],
            'total': result['total'],
            'page': page,
            'limit': limit
        }
    })